<template>
  <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm">
    <el-col :span="12">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName" />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" show-password />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="真实姓名" prop="fullName">
        <el-input v-model="ruleForm.fullName" />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="ruleForm.mobile" />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="所属角色" prop="roles">
        <el-select
          v-model="ruleForm.role"
          multiple
          collapse-tags
          style="width:100%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker
          v-model="ruleForm.birthday"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio v-for="item in sex" :key="item.label" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-col>

    <el-col :span="12">
      <el-form-item label="头像上传" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="auth"
          name="form"
        >
          <img v-if="avatar" :src="avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
    </el-col>
    <el-col :span="24">
      <el-form-item label="用户介绍">
        <el-input v-model="ruleForm.introduction" type="textarea" :rows="3" />
      </el-form-item>
    </el-col>
  </el-form>
</template>

<script>
import { getRoles } from '@/api/role'
import { mapGetters } from 'vuex'
import { update, get } from '@/api/user'
export default {
  name: 'VueElementAdminEdit',
  props: {
    user: {
      type: Object,
      default() {
        return { }
      }
    }
  },

  data() {
    return {
      ruleForm: {
        id: '',
        userName: '',
        password: '',
        fullName: '',
        mobile: '',
        birthday: '',
        sex: 1,
        avatar: '',
        introduction: '',
        role: []
      },
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        mobile: [
          { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ]
      },
      sex: [{
        label: '男',
        value: 1
      },
      {
        label: '女',
        value: 2
      }],
      roles: [],
      avatar: ''
    }
  },
  computed: {
    uploadUrl() {
      return `${process.env.VUE_APP_BASE_API}uploadfile`
    },
    ...mapGetters([
      'token'
    ]),
    auth() {
      return { Authorization: `Bearer ${this.token}`
      }
    }
  },
  mounted() {
    get({ id: this.user.id }).then(res => {
      /** 错误示例 */
      // this.ruleForm = res.data
      // this.ruleForm.role = res.data.adminRoleDtos.map(x => x.roleId)

      /** 数组没有响应式的解决方案一 */
      // const user = res.data
      // user.role = res.data.adminRoleDtos.map(x => x.roleId)
      // this.ruleForm = user

      /** 数组没有响应式的解决方案二 */
      Object.assign(this.ruleForm, res.data)
      this.ruleForm.role = res.data.adminRoleDtos.map(x => x.roleId)

      this.avatar = `${process.env.VUE_APP_BASE_API}${res.data.avatar}`
    })

    getRoles().then(res => {
      this.roles = res.data
    })
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const _this = this
          update({ id: this.ruleForm.id }, this.ruleForm).then(res => {
            this.$message({
              message: res.message,
              type: 'success',
              onClose: () => {
                _this.$emit('success')
              }
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(res, file) {
      this.avatar = URL.createObjectURL(file.raw)
      this.ruleForm.avatar = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
  <style>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 18px;
      color: #8c939d;
      width: 38px;
      height: 38px;
      line-height: 38px;
      text-align: center;
    }
    .avatar {
      width: 38px;
      height: 38px;
      display: block;
    }
  </style>

